import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_aygsh/base/Constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_saver/image_saver.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_aygsh/base/application.dart';
import 'package:flutter_aygsh/http/Api.dart';
import 'package:flutter_aygsh/http/HttpUtil.dart';
import 'package:flutter_aygsh/util/LoadingUtil.dart';
import 'package:flutter_aygsh/util/SignUtil.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:wechat_kit/wechat_kit.dart';

class ShareGoodsPicPage extends StatefulWidget {
  List<String> pics;
  String goods_id, goods_name, price, old_price, img;
  ShareGoodsPicPage(
      {Key key,
      // @required this.pics,
      this.goods_id,
      this.goods_name,
      this.price,
      this.img,
      this.old_price})
      : super(key: key);

  @override
  _ShareGoodsPicPageState createState() => _ShareGoodsPicPageState();
}

class _ShareGoodsPicPageState extends State<ShareGoodsPicPage> {
  List<bool> bools = new List();
  StreamSubscription<WechatSdkResp> _share;
  GlobalKey key = new GlobalKey();
  String group_name = "", userName = "", avatar, uid = "", urlImg = "";
  String origin = "";
  Wechat _wechat = Wechat()
    ..registerApp(appId: WX_APPID, universalLink: WECHAT_UNIVERSAL_LINK);
  bool isShow = false;
  @override
  void initState() {
    super.initState();
    // for (int i = 0; i < widget.pics.length; i++) {
    //   bools.add(false);
    // }
    userName = APPLIC.userInfoMap['user_detail']['nickname'] == null
        ? APPLIC.userInfoMap['user_msg']['phone']
        : APPLIC.userInfoMap['user_detail']['nickname'];
    avatar = APPLIC.userInfoMap['user_detail']['avatar'];
    uid = APPLIC.userInfoMap['user_msg']['uid'].toString();
    setState(() {});
    checkWx();
    getImg();
  }

  getImg() async {
    Map map = new Map();
    map['scene'] = "uid=" + uid + "&goods_id=" + widget.goods_id;
    map['page'] = "pages/live/splash";
    map['sign_type']="dmsh.UserAccount.getWxacodeunlimit";
    Response<String> response = await HttpUtil().post(
        Api.BaseUrl + "/index.php/wap/UserAccount/getWxacodeunlimit",
        data: getSign(map));
        print(map);
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      origin = userMap['data']['img'];
      urlImg = userMap['data']['img']
          .toString()
          .replaceAll("\\", "/")
          .replaceFirst(".", "");
      setState(() {});
    }
  }

  checkWx() async {
    if (await _wechat.isInstalled()) {
      _share = _wechat.shareMsgResp().listen(_listenShareMsg);
      setState(() {
        isShow = false;
      });
    } else {
      setState(() {
        isShow = true;
      });
    }
  }

  _capturePng(plat) async {
    try {
      RenderRepaintBoundary boundary = key.currentContext.findRenderObject();
      var image = await boundary.toImage(pixelRatio: 3.0);
      ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();
      _capturePath(pngBytes,
          Platform.isIOS ? pngBytes : pngBytes.buffer.asInt8List(), plat);
      Navigator.of(context).pop(1);
      return pngBytes;
    } catch (e) {
      Navigator.of(context).pop(1);
      print(e);
    }
    return null;
  }

  _capturePath(pngBytes, byteData, plat) async {
    String fileName = DateTime.now().millisecondsSinceEpoch.toString() + ".png";
    if (Platform.isAndroid) {
      var status = await Permission.storage.status;

      if (status.isGranted) {
        Directory documentsDirectory = await getExternalStorageDirectory();
        String path = documentsDirectory.path + "/xiongmao";
        bool has = await Directory(path).exists();
        if (!has) {
          await Directory(path).create();
        }
        File file = await File(path + "/$fileName").writeAsBytes(pngBytes);
        if (plat != null) {
          await _wechat.shareImage(
            scene: plat,
            imageUri: Uri.file(file.path),
          );
        } else {
          String result = await ImageGallerySaver.saveFile(path + "/$fileName");
          if (result != null) {
            Fluttertoast.showToast(msg: "保存成功");
          } else {
            Fluttertoast.showToast(msg: "保存失败");
          }
        }
      } else {
        await Permission.storage.request();
      }
    } else {
      Directory documentsDirectory = await getApplicationDocumentsDirectory();
      String path = documentsDirectory.path;
      File files = await File(path + "/$fileName").writeAsBytes(pngBytes);
      // final res = await _imageSaver.saveImage(
      // imageBytes: pngBytes, imageName: fileName, directoryName: path);
      // File file = File(path + "/$fileName");
      if (files == null) {
        if (plat != null) {
          Fluttertoast.showToast(msg: "分享失败");
        } else {
          Fluttertoast.showToast(msg: "保存成功");
        }
        return;
      }
      bool result = await ImageGallerySaver.saveFile(path + "/$fileName");
      // ImageGallerySaver.saveImage(imageBytes:pngBytes)
      // print(result.toString());
      // File savedFile = await ImageSaver.toFile(fileData: byteData);
      //  Fluttertoast.showToast(msg: "保存成功");
      // if (!file.existsSync()) {
      //   file.createSync();
      //   file.writeAsBytes(byteData);
      // }
      // if (res) {

      if (result) {
        //   File file = File(path + "/$fileName");
        //   // print(file.existsSync());
        if (plat != null) {
          // const url = "weixin://";
          // if (await canLaunch(url)) {
          //   await launch(url);
          // } else {
          //   print('分享失败');
          // }
          await _wechat.shareImage(
            scene: plat,
            imageUri: Uri.file(path + "/$fileName"),
          );
        } else {
          Fluttertoast.showToast(msg: "保存成功");
        }
        //
        // } else {
        //   Fluttertoast.showToast(msg: "保存失败");
        // }
      } else {
        Fluttertoast.showToast(msg: "失败");
      }
    }
  }

  void _listenShareMsg(WechatSdkResp resp) {
    if (Platform.isIOS) {
      if (resp.errorCode == 0) {
        Fluttertoast.showToast(msg: "分享成功");
      } else {
        Fluttertoast.showToast(msg: "分享失败");
      }
    }
  }

/*
   * 下载文件
   */
  downloadFile(urlPath, savePath, plat) async {
    Response response;
    File file = File(savePath);
    if (!file.existsSync()) {
      file.createSync();
    }
    try {
      response = await new Dio().download(urlPath, savePath,
          onReceiveProgress: (int count, int total) {
        //进度
        // print("$count $total");
      });
      Navigator.of(context).pop(1);
      print(response.statusCode);
      if (response.statusCode == 200) {
        // Fluttertoast.showToast(msg: '下载成功');
        await _wechat.shareImage(
          scene: plat,
          imageUri: Uri.file(file.path),
        );
      }
      // print('downloadFile success---------${response.data}');
    } on DioError catch (e) {
      Fluttertoast.showToast(msg: '分享失败');
      Navigator.of(context).pop(1);

      // print('downloadFile error---------$e');
    }
    return response.data;
  }

  @override
  void dispose() {
    if (_share != null) {
      _share.cancel();
    }
    if (origin != '') {
      Map map = new Map();
      map['img'] = origin;
      map['sign_type']="dmsh.UserAccount.unlinkWxacode";
      HttpUtil().post(Api.BaseUrl + "/index.php/wap/UserAccount/unlinkWxacode",
          data: getSign(map));
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text('微信分享',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: black)),
        backgroundColor: white,
        brightness: Brightness.light,
        iconTheme: IconThemeData(color: black_99),
        elevation: 0.5,
      ),
      body: new Container(
          width: double.infinity,
          child: new Column(children: <Widget>[
            Expanded(child: Center()),
            RepaintBoundary(
              key: key,
              child: Container(
                color: Colors.white,
                width: MediaQuery.of(context).size.width * 3 / 4,
                // height: MediaQuery.of(context).size.width * 9 / 10 + 30,
                child: Column(
                  children: <Widget>[
                    ClipRRect(
                      child: CachedNetworkImage(
                        imageUrl: widget.img.contains("http")
                            ? widget.img
                            : Api.ImgBaseUrl + widget.img,
                        width: MediaQuery.of(context).size.width * 3 / 4,
                        height: MediaQuery.of(context).size.width * 3 / 4,
                        fit: BoxFit.fitWidth,
                      ),
                      borderRadius: BorderRadius.circular(0),
                    ),
                    Container(
                      color: white,
                      // width: ScreenUtil.getInstance().setHeight(370),
                      padding: EdgeInsets.fromLTRB(15, 8, 15, 5),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          Expanded(
                              child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.end,
                                  children: <Widget>[
                                    Text(MONEY,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(NORMAL_FONT_SIZE),
                                            color: Colors.red)),
                                    Text(widget.price,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(NORMAL_FONT_SIZE + 10),
                                            color: Colors.red)),
                                    Text(
                                      " " + MONEY + widget.old_price,
                                      style: TextStyle(
                                          color: Colors.black54,
                                          decoration:
                                              TextDecoration.lineThrough,
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(NORMAL_FONT_SIZE)),
                                    ),
                                  ]),
                              Container(
                                height: 2,
                              ),
                              Text(
                                widget.goods_name,
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    color: Colors.black87,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(NORMAL_FONT_SIZE - 2)),
                              ),
                            ],
                          )),
                          Container(
                            width: 5,
                          ),
                          urlImg == ""
                              ? Center()
                              : Column(
                                  children: <Widget>[
                                    CachedNetworkImage(
                                        imageUrl: Api.BaseUrl + urlImg,
                                        width: ScreenUtil.getInstance()
                                            .setHeight(100)),
                                  ],
                                )
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
            Expanded(child: Center()),
            Container(
              padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(15)),
              margin: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(1), 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () async {
                  if (isShow) {
                    Fluttertoast.showToast(msg: "安装微信客户端后才能分享哦");
                    return;
                  }
                  showDialog(
                      context: context,
                      barrierDismissible: false,
                      builder: (_) {
                        return new NetLoadingDialog(
                          loadingText: "分享中...",
                          bgColor: Color.fromARGB(255, 0, 0, 0),
                          requestCallBack: null,
                          outsideDismiss: false,
                        );
                      });
                  _capturePng(WechatScene.SESSION);
                },
                child: new Row(
                  children: <Widget>[
                    Image.asset("images/wx.png",
                        width: ScreenUtil.getInstance().setHeight(60)),
                    Container(width: 10),
                    Expanded(
                      child: Text(
                        '分享到微信',
                        style: TextStyle(
                            fontSize:
                                ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.grey,
                      size: 20,
                    )
                  ],
                ),
              ),
            ),
            Offstage(
              offstage: false,
              child: Container(
                padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(15)),
                margin: EdgeInsets.fromLTRB(
                    0, ScreenUtil.getInstance().setHeight(1), 0, 0),
                color: Colors.white,
                child: new GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () async {
                    if (isShow) {
                      Fluttertoast.showToast(msg: "安装微信客户端后才能分享哦");
                      return;
                    }
                    showDialog(
                        context: context,
                        barrierDismissible: false,
                        builder: (_) {
                          return new NetLoadingDialog(
                            loadingText: "分享中...",
                            bgColor: Color.fromARGB(255, 0, 0, 0),
                            requestCallBack: null,
                            outsideDismiss: false,
                          );
                        });
                    _capturePng(WechatScene.TIMELINE);
                  },
                  child: new Row(
                    children: <Widget>[
                      Image.asset("images/pyq.png",
                          width: ScreenUtil.getInstance().setHeight(60)),
                      Container(width: 10),
                      Expanded(
                        child: Text(
                          '分享到朋友圈',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: Colors.black87),
                        ),
                      ),
                      Icon(
                        Icons.arrow_forward_ios,
                        color: Colors.grey,
                        size: 20,
                      )
                    ],
                  ),
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(15)),
              margin: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(1), 0, 0),
              color: Colors.white,
              child: new GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () async {
                  showDialog(
                      context: context,
                      barrierDismissible: false,
                      builder: (_) {
                        return new NetLoadingDialog(
                          loadingText: "保存中...",
                          bgColor: Color.fromARGB(255, 0, 0, 0),
                          requestCallBack: null,
                          outsideDismiss: false,
                        );
                      });
                  _capturePng(null);
                },
                child: new Row(
                  children: <Widget>[
                    Image.asset("images/save.png",
                        width: ScreenUtil.getInstance().setHeight(60)),
                    Container(width: 10),
                    Expanded(
                      child: Text(
                        '保存到手机相册',
                        style: TextStyle(
                            fontSize:
                                ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                            color: Colors.black87),
                      ),
                    ),
                    Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.grey,
                      size: 20,
                    )
                  ],
                ),
              ),
            ),
            Container(
              height: 30,
            ),
          ])),
    );
  }

/*
   * 下载文件
   */
  downloadFiles(int count) async {
    List<File> files = new List();
    for (int i = 0; i < bools.length; i++) {
      if (bools[i]) {
        String urlPath;
        Dio dio = Dio();
        dio.options.responseType = ResponseType.bytes;
        urlPath = widget.pics[i].contains("http")
            ? widget.pics[i]
            : Api.ImgBaseUrl + widget.pics[i];
        var response = await dio.get(urlPath);
        File savedFile = await ImageSaver.toFile(fileData: response.data);
        if (savedFile != null) {
          files.add(savedFile);
          if (files.length == count) {
            break;
          }
        }
      }
    }
    Navigator.of(context).pop(1);
    Fluttertoast.showToast(msg: '保存成功');
  }
}
